using System;
using Dimebrain.TweetSharp.Core.Caching;

namespace Dimebrain.TweetSharp.Core.Web.Query
{
    partial class WebQueryBase
    {
        public virtual string ExecutePost(string url, string key, IClientCache cache)
        {
            return ExecuteWithCache(cache, url, key, (c, u) => ExecutePostAndCache(cache, url, key));
        }

        public virtual string ExecutePost(string url, string key, IClientCache cache, DateTime absoluteExpiration)
        {
            return ExecuteWithCacheAndAbsoluteExpiration(cache, url, key, absoluteExpiration,
                                                         (c, u, e) =>
                                                         ExecutePostAndCacheWithExpiry(cache, url, key,
                                                                                       absoluteExpiration));
        }

        public virtual string ExecutePost(string url, string key, IClientCache cache, TimeSpan slidingExpiration)
        {
            return ExecuteWithCacheAndSlidingExpiration(cache, url, key, slidingExpiration,
                                                        (c, u, e) =>
                                                        ExecutePostAndCacheWithExpiry(cache, url, key, slidingExpiration));
        }

        private string ExecutePostAndCache(IClientCache cache, string url, string key)
        {
            var result = ExecutePost(url);
            cache.Insert(CreateCacheKey(key, url), result);
            return result;
        }

        private string ExecutePostAndCacheWithExpiry(IClientCache cache, string url, string key,
                                                     DateTime absoluteExpiration)
        {
            var result = ExecutePost(url);
            cache.Insert(CreateCacheKey(key, url), result, absoluteExpiration);
            return result;
        }

        private string ExecutePostAndCacheWithExpiry(IClientCache cache, string url, string key,
                                                     TimeSpan slidingExpiration)
        {
            var result = ExecutePost(url);
            cache.Insert(CreateCacheKey(key, url), result, slidingExpiration);
            return result;
        }
    }
}